package ast;

import java.util.ArrayList;

public class OutputStatement extends Statement {
	public String printString;
	// .format()里面的东西，表达式Expression
	public ArrayList<AstItem> formatExpressions = new ArrayList<AstItem>();
	
	public void preprocess(AstItem father) {
		for (AstItem x : formatExpressions) {
			x.preprocess(this);
		}
	}

	public String getFormatString(AstItem x) {
		assert x instanceof Expression;
		String type = ((Expression) x).dataType;
		if (type.equals("int")) return "%d";
		else if (type.equals("long")) return "%ld";
		else if (type.equals("longlong")) return "%lld";
		else if (type.equals("double")) return "%lf";
		else if (type.equals("char")) return "%c";
		else {
			assert type.equals("string");
			return "%s";
		}
	}
	
	public String toString() {
		int startIndex = 0;
		int expressionIndex = 0;
		StringBuilder sb = new StringBuilder(printString);
		while (true) {
			int findIndex = sb.indexOf("{}", startIndex);
			if (findIndex == -1) break;
			else {
				String replaceString = getFormatString(formatExpressions.get(expressionIndex));
				sb.replace(findIndex, findIndex + 2, replaceString);
				expressionIndex += 1;
				startIndex = findIndex + replaceString.length();
			}
		}
		String result = "printf(" + sb.toString() + "";
		for (AstItem x : formatExpressions) {
//			System.out.println(x.getClass() + "***");
			result += ", " + x.toString();
		}
		result += ");";
		return result;
	}
	
	@Override
	public String toJsonString() {
		String json = "{";
		json += "\"Type\": \"Statement-" + type.toString() + "\",";
		json += "\"PrintString\": " + printString + ",";
		json += "\"FormatExpressions\": [";
		for (AstItem astItem: formatExpressions) {
			json += astItem.toJsonString() + ",";
		}
		json += "]";
		json += "}";
		return json;
	}
}
